package com.kakarote.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.kakarote.core.common.cache.CommonKey;
import com.kakarote.core.redis.RedisImpl;
import com.taobao.api.ApiException;
import lombok.extern.log4j.Log4j;

@Log4j
public class DingTalkWorkNoticeUtils {

    private static final String GET_TOKEN_URL = "https://oapi.dingtalk.com/gettoken";
    private static final String GET_BY_MOBILE = "https://oapi.dingtalk.com/topapi/v2/user/getbymobile";

    private static final String GET_BY_DEPT = "https://oapi.dingtalk.com/topapi/v2/department/listsub";//获取部门下所有员工userid列表
    private static final String GET_BY_USER_LIST = "https://oapi.dingtalk.com/topapi/v2/user/list";//获取部门下所有员工userid列表


    private static final String ASYNC_SEND_V2_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2";
    private static final String DEFAULT_APP_KEY = "dingwflvxfrm28vt645n";
    private static final String DEFAULT_APP_SECRET = "TzQc-f9IwmL8ihsaIV1kbmp31wmb2oUtr_5NXATmBsgC4uGi_CKCJUqaC7OjExnH";
    private static final Long DEFAULT_AGENT_ID = 3332402139L;
    private static final String DEFAULT_REQUEST_METHOD = "GET";

    private String appKey;
    private String appSecret;
    private Long agentId;
    private String reqMethod;


    public DingTalkWorkNoticeUtils() {
        this(DEFAULT_APP_KEY, DEFAULT_APP_SECRET, DEFAULT_AGENT_ID, DEFAULT_REQUEST_METHOD);
    }

    public String getGetAccessToken(RedisImpl redisImpl) throws ApiException {
        boolean exists = redisImpl.exists(CommonKey.ACCESS_TOKEN);
        String accessToken = null;
        if(!exists){
            accessToken = getTokenResponse();
            redisImpl.setex(CommonKey.ACCESS_TOKEN,7200,accessToken);
        }else{
            accessToken = redisImpl.get(CommonKey.ACCESS_TOKEN);
        }
        return accessToken;
    }

    public DingTalkWorkNoticeUtils(String appKey, String appSecret, Long agentId, String reqMethod) {
        this.appKey = (appKey != null && !appKey.isEmpty()) ? appKey : DEFAULT_APP_KEY;
        this.appSecret = (appSecret != null && !appSecret.isEmpty()) ? appSecret : DEFAULT_APP_SECRET;
        this.agentId = (agentId != null) ? agentId : DEFAULT_AGENT_ID;
        this.reqMethod = (reqMethod != null && !reqMethod.isEmpty()) ? reqMethod : DEFAULT_REQUEST_METHOD;
    }

    /**
     * 获取AccessToken
     */
    public String getTokenResponse() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(GET_TOKEN_URL);
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setAppkey(appKey);
        req.setAppsecret(appSecret);
        req.setHttpMethod(reqMethod);
        OapiGettokenResponse rsp = client.execute(req);
        System.out.println("AccessToken() = " + rsp.getAccessToken());
        return rsp.getAccessToken();//be39ee5f3e883144897189af8345c822  usserid:046969163326152250   //我的"unionid":"djiS0jEf08iSiiBMqr1b1XTUQiEiE",
    }

    /**
     * 根据手机号获取UserId
     */
    public String getUserIdByMobile(String accessToken, String mobileNum) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(GET_BY_MOBILE);
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.setMobile(mobileNum);
        OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);

        JSONObject jsonObject = JSON.parseObject(rsp.getBody());
        JSONObject result = jsonObject.getJSONObject("result");
        String userid = result.getString("userid");
        return userid;
    }

    /**
     * 发送工作通知消息
     */
    public boolean sendWorkNotice(String accessToken, String msgType, String content, String userId) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(ASYNC_SEND_V2_URL);

        OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
        req.setAgentId(agentId);
        req.setUseridList(userId);

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype(msgType);
        OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();
        text.setContent(content);
        msg.setText(text);

        req.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, accessToken);
        return rsp.isSuccess();
    }

    /**
     * 获取部门信息
     */
    public JSONArray getDepList(String accessToken) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(GET_BY_DEPT);
        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
        OapiV2DepartmentListsubResponse rsp = client.execute(req, accessToken);
        JSONObject jsonObject = JSON.parseObject(rsp.getBody());
        JSONArray result = jsonObject.getJSONArray("result");
        return result;
    }

    /**
     * 根据部门ID查询员工数据
     * @param accessToken
     * @param deptId
     * @return
     */
    public String getUserListByDepId(String accessToken, Long deptId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(GET_BY_USER_LIST);
            OapiV2UserListRequest req = new OapiV2UserListRequest();
            req.setDeptId(Long.valueOf(deptId));
            req.setCursor(1L);
            req.setSize(99L);
            OapiV2UserListResponse rsp = client.execute(req, accessToken);
            String result = rsp.getBody();
            return result;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String msgType = "text";

    public boolean sendDing(String accessToken,String dingUserId,String content) throws ApiException {
        // 调用 sendWorkNotice 发送消息
        return sendWorkNotice(accessToken, msgType, content, dingUserId);
    }
}


